import { ThreeBase } from "../js/ThreeBase";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import {
    AmbientLight, Box3, DirectionalLight,
    LinearFilter, RGBAFormat, Vector2,
    Mesh, Spherical, Vector3, WebGLMultisampleRenderTarget, WebGLRenderTarget, Group, Color
} from "three";
import { TWEEN } from "../js/TWEEN";
import { PixelOutlinePass } from '../js/PixelOutlinePass'
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer";
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass";
import { WEBGL } from "three/examples/jsm/WebGL";
import { CSS2DObject } from '../js/CSS2DRenderer';

// 导入传感器的 请求
import { chuanGanqi, gongweiColor,shishi } from '../api/demo'
import { color } from "echarts";

var sets=null;
var airlist=0;
var temperaturelist=0;
var humiditylist=0;
export class View extends ThreeBase {
    
    constructor(dom, $) {
        super(dom);
        this.$ = $;
        this.setComposer();
        this.initModel();
        this.initLight();
        
    }
    // shishidata(){

    // }
    // ,

    setComposer() {
        this.renderer.autoClear = true;
        const ratio = window.devicePixelRatio;
        const w = this.width * ratio,
            h = this.height * ratio;
        let renderTargetParameters = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat, stencilBuffer: true };
        let renderTarget = new WebGLRenderTarget(window.innerWidth, window.innerHeight, renderTargetParameters);
        if (WEBGL.isWebGL2Available()) {
            const size = this.renderer.getDrawingBufferSize(new Vector2());
            renderTarget = new WebGLMultisampleRenderTarget(size.width, size.height, {
                format: RGBAFormat,
                magFilter: LinearFilter,
                minFilter: LinearFilter
            });
        }

        this.composer = new EffectComposer(this.renderer, renderTarget);
        this.composer.setSize(w, h);
        this.composer.setPixelRatio(window.devicePixelRatio);
        this.renderScene = new RenderPass(this.scene, this.camera);
        this.composer.addPass(this.renderScene);
        this.pix = new PixelOutlinePass(this.camera);
        this.pix.thickness = 1.5;
        this.composer.addPass(this.pix);
    }


    resize = () => {
        this.initWidthAndHeight();
        this.camera.aspect = this.width / this.height;
        this.camera.updateProjectionMatrix();
        this.composer.setSize(this.width, this.height);
        this.pix.setSize(this.width, this.height);
        this.renderer.setSize(this.width, this.height);
        this.css2DRenderer.setSize(this.width, this.height);
    }

    render = () => {
        this.css2DRenderer.render(this.scene, this.camera);
        this.composer.render();
        TWEEN.update();
        this.eventList.runAll();
        this.controls.update();
    }
    
    // 点击工位
    initClick(model) {
        
        // var vv=object.parent.parent.name
        // console.log("点击后的数据",99999)
        //  在这里加上 async  
        document.body.addEventListener('click', e => {
            
            // console.log("点击后的数据",888888)
          var vv = this.sets
          // console.log('this.sets',this.sets);
            const raycasters = this.getRaycastersByObject(e, this.scene.children);
            if (raycasters.length > 0) {
                this.$.show = false;
                const { object, point } = raycasters[0];				
                // console.log("objectobjectobject",object.name);
                //   如果 点击的是监控 把对应监控的名字 赋值给变量  并弹出 监控框
                if (object.name == 'AM218_029_CCTV') {
                    this.$.cameraName = object.name;
                    this.$.show = true;
                    //  如果 点击的是 相机监控   就弹出  对应的相机名字  和弹框
                } else if (object.name.includes('camera')) {
                    this.$.cameraName = object.parent.parent.name;
                    this.$.show = true;
                } else {					
					// console.log("你进来了阿")
                    let station = object.parent.parent;
					// console.log("station",station.name)
                    // console.log("station2",object.parent.parent.name)
                    if(object.parent.parent.name!==''){
                        // console.log("点击到了工位")
                        console.log("station",object.parent.parent.name)
                        object.parent.parent.name
                        this.$.parentname = object.parent.parent.name;
                        this.$.show = true;               
                        // console.log("工位的所有数据",object)
                        // console.log("工位的坐标",object.parent.parent.position)
                        // console.log("工位的颜色",object.material.color)   
                      
                    //   console.log('this.sets',this.sets);
                     
                    }
                    let isOn = station.isOn;					
                    // console.log(await equipmentAbnormal(),'000');
                    // const { data:res } =  getAllChannels()  // 测试 后端返回的数据
                    // console.log(res.data.channels,'999000');
                    // station.traverse((m) => {
                    //     if (m instanceof Mesh) {
                    //         if (m.material.name == '02 - Default') {
					// 			console.log("你点击了哦")
								
								
								
								
                    //             //  点击同一个工位 模型    第一次 和第二次 出现的颜色
                    //             if (isOn) {
                    //                 // var colors = 0x008000  // 在请求文件 拿到后端返回的颜色, 然后再把颜色 保存到这里
                    //                 // m.material.color.set(0x00ffff);
                    //                 // // m.material.color.set(colors); // 点击后的工位颜色
                    //                 // var colors = '#ffffff'
                    //                 // m.material.color.set(colors); // 点击后的工位颜色
									
                    //             } else {
                    //                 // m.material.color.setRGB(1,0.23,.0);
                    //                 m.material.color.setRGB(0, 0, 205); // 这是什么颜色
                    //             }
                    //         }
                    //     }
                    // });
                    station.isOn = !isOn;
                }

            }
        }, true);

        this.container.addEventListener('mousemove', e => {
            const raycasters = this.getRaycastersByObject(e, this.stations);
            this.pix.clearOutlines();
            if (raycasters.length > 0) {
                const { object } = raycasters[0];
                let meshes = [];
                if (object.name != 'AM218_029_CCTV') {
                    let station = object.parent.parent;
                    station.traverse(m => {
                        if (m instanceof Mesh) {
                            meshes.push(m);
                        }
                    });
                } else {
                    meshes = [object];
                }
                //   鼠标在指定元素身上移动
                // this.pix.setOutline(0x00ffff,meshes);
                this.pix.setOutline(0x800080, meshes);
            }
        });
    }
    
    

    // 点击模型, 重点这两个函数
    async initModel() {
        //  创建一个map 结构
        var map = new Map();
        var wendu = null;
        var shidu = null;
        var chuanganqi = null;
        var loushui = null;
        //  这个是调整 模型位置
        // this.scene.position.y = 10;
        // this.scene.position.z = 6;

        // this.scene.background = this.loadTexture('/bg2.png');
        // this.scene.fog = new Color(0x008000)
        // let { envMap } = await this.getCubeMapTexture('venice_sunset_1k.jpg');
        let { envMap } = await this.getCubeMapTexture('footprint_court_2k.pic');
        this.envMap = envMap;

        let group = new Group();

        // let xj = await this.loadGLTFModel('/cctv.glb');
        // let model = xj.scene.getObjectByName('AM218_029_CCTV');
        this.stations = [];
      
        let { scene } = await this.loadGLTFModel('/bangongshi.glb');

        let glass = ['Box029', 'Box010', 'Object', 'Box036', 'Box033'];
        var shuliang = 0;

        // gongweiColor().then(res => {
        //     if (res.data.code == 200) {
        //         console.log('请求成功:');
        //         console.log(res.data.result, '工位颜色的接口数据===========11111111');

        //     }
        // }).catch(err => {
        //     console.log(err, ' 工位颜色的接口数据22222222222')
        // })
        //工位颜色接口
  
        var t = null;
        t = setTimeout(time, 2000);
        async function time() {  
            shishi().then(res =>{
              // console.log("实时")
              // console.log(res.data.result)
                if(res.data.code==200){
                    airlist=res.data.result.air
                    temperaturelist=res.data.result.temperature
                    humiditylist=res.data.result.humidity
                    // console.log(airlist,temperaturelist,humiditylist)
                }
        })
        t = setTimeout(time, 2000);
      }
    
    
     
        gongweiColor().then(res => {
            if (res.data.code == 200) {
                console.log('请求成功:');
                console.log(res.data.result, '工位颜色的接口数据===========11111111');
                var arr = res.data.result
                // console.log("arr", arr)
                var arrcode=arr.code

                for(let i = 0; i < arr.length; i++){
                    // console.log("arr[i].code", arr[i].code)
                    map.set(arr[i].code, arr[i].color);
                }
                // console.log(map, '-========-======-----------------');
            }
        }).catch(err => {
            console.log(err, ' 工位颜色的接口数据请求失败。')
        })

        scene.traverse(m => {
            if (m instanceof Mesh) {
                if (glass.includes(m.name)) {
                    m.material.transparent = true;
                    m.material.opacity = .2;
                    m.material.side = 0;
                } else if (m.name == 'dimian') {
                    m.receiveShadow = true;
                } else {
                    m.castShadow = true;
                }
                if (m.name == 'waiqiang') {
                    m.material.envMap = this.envMap;
                    m.material.metalness = .5;
                    m.material.roughness = .5;
                    m.material.color.set(0xF8F8FF);
                }
                m.material = m.material.clone();
                if (m.material.name == '02 - Default') {

                }
                if(m.name=='Box013'||m.name=='Box014'){
                    m.visible = false;
                }
            }

            // ====================================================================================================================
            if (m.name.indexOf('station') >= 0 && m.type == 'Object3D' && m.children.length == 2) {
                // console.log("外面: ", m.name)
                m.traverse(m => {
                    if (m instanceof Mesh) {
                        if (m.material.name == 'Material #108') {
                            shuliang++;

                            // console.log(m.name)
                            // if(m.name == 'station1001') {
                            //     m.name.color.set(0x00ff00) // 绿色

                            // }
                            // m.material.color.set(0x00ff00);  // 绿色
                            
                            m.material.color.set(0xFF0000);
                        }
                    }
                });
                this.stations.push(m);
            }

            if (m.type == "Object3D" && m.name.indexOf('camera') >= 0) {
                m.position.y -= 2.2;
                this.stations.push(m);
            }
        });
        // console.log("slian:  " + shuliang);

        /**
         * 设置所有椅子为绿色
         */
        // this.stations.forEach(m=>{
        //     m.traverse(m=>{

        //         if(m instanceof Mesh){
        //             if(m.material.name=='Material #108'){
        //                 // console.log(m.name)
        //                 // m.material.color.set(0x00ff00);  // 绿色
        //                 m.material.color.set(0xFF0000);
        //             }
        //         }
        //     });
        // });
        //改变工位颜色
        setTimeout(() => {
            this.stations.forEach(m => {
                m.traverse(m => {
                    if (m instanceof Mesh) {
                        if (m.material.name == 'Material #108') {
                            // console.log("map", map.get(m.parent.parent.name))
                            if(map.get(m.parent.parent.name)){
                                // 改变工位的颜色
                                m.material.color.set(map.get(m.parent.parent.name)); 
                                
                            }
                        }
                    }
                });
            });
            
        }, 1000);

     
      
        // console.log("温湿度温湿度",m)
        ['温度', '湿度', '空气'].forEach((m, i) => {
            let span = document.createElement('span');
            // console.log("res.data",span)
            Object.assign(span.style, {
                color: 'white',
                borderRadius: '2px',
                border: '1px solid white',
                fontSize: '1px',
                background: 'rgba(0,0,0,.5)',
            });
     
            
            let a = new CSS2DObject(span);
            var status = true;
            const cssy = -16;
            const cssyy = -14;
            const cssyyy = -12;

         
            if (m == '温度') {          
                // a.position.copy(new Vector3(-25,  -16,  8.830763))
                a.position.copy(new Vector3(-25,  -16,  8.830763))               
                setInterval(() => {
                 
                    // console.log(tt)
                    // span.innerHTML = wendu + "℃"
                    // span.innerHTML = m + ': ' + (Math.random() * 30).toFixed(2) + "℃"
                    span.innerHTML = m + ': ' + temperaturelist + "℃"
                    
                }, 2000);

            } else if (m == "湿度") {
                a.position.copy(new Vector3( -25,  -14,  8.830763));
                setInterval(() => {
                    span.innerHTML = m + ': ' + humiditylist + "℃";
                    // span.innerHTML = m + ': ' + chuanganqi;
                }, 2000);
            }else{
              a.position.copy(new Vector3( -25,  -12,  8.830763));
              setInterval(() => {
                
                span.innerHTML = m + ': ' + airlist;
                // span.innerHTML = m + ': ' + chuanganqi;
            }, 2000);
            }

            
            this.scene.add(a);
            group.add(scene);
        });

        this.setControls(group);

        this.scene.add(group);

        this.renderer.setAnimationLoop(this.render.bind(this));
        window.addEventListener('resize', this.resize.bind(this));

        this.initClick(group);
    }
   

    setControls(model) {
        const { camera } = this;
        let box3 = new Box3().setFromObject(model);
        let center = box3.getCenter(new Vector3());
        model.position.add(model.position.clone().sub(center));
        // model.position.y -= 10;
        camera.position.copy(new Vector3().setFromSpherical(
            new Spherical(box3.getSize(new Vector3()).length(), -Math.PI / 4, 0)).clone());
        // camera.position.y += 10;
        camera.lookAt(center);


        // Vector3 {x: 0.6881772714653491, y: 27.05423983435097, z: -41.451426167440715} 
        // Vector3 {x: -0.4759521617842959, y: -2.406329498099123, z: 1.0915007583610312}
        this.camera.position.copy(new Vector3(-0.5511710978805625, 33.881070372124334,  -37.78070895955103));
        this.camera.lookAt(new Vector3(-0.48755424534927294,  -2.872254968545357,  -0.36080517436610743));

        const controls = new OrbitControls(camera, this.container);
        controls.minPolarAngle = 0;
        controls.maxPolarAngle = Math.PI / 2;
        controls.zoomSpeed = 2.0;
        controls.maxDistance = 2000;
        this.controls = controls;
        this.controls.target.copy(new Vector3(-0.48755424534927294,  -2.872254968545357,  -0.36080517436610743));
        this.controls.update();
    }

    initLight() {
        // this.renderer.shadowMap.enabled = true;
        // this.renderer.shadowMap.type = PCFSoftShadowMap;
        this.scene.add(new AmbientLight(0xffffff, .5));
        let dir = new DirectionalLight(0xffffff, .4);
        // dir.castShadow = true;
        // const size = 80;
        // dir.shadow.camera.top = size;
        // dir.shadow.camera.bottom = -size;
        // dir.shadow.camera.left = -size;
        // dir.shadow.camera.right = size;
        // dir.shadow.mapSize.x = 1024;
        // dir.shadow.mapSize.y = 1024;
        // dir.position.set(-size, size, size);
        this.scene.add(dir);
    }

    
    
} 


export function attempt () {
    //js数据向vue发送
    let taozi =sets
    return taozi
}